import Taro from '@tarojs/taro';
import { RequestOption, RequestResponse, RequestData, UploadFileOption } from './type';
import { log } from '../appLog';

const config = {
  mode: process.env.TARO_APP_MODE,
  dev: {
    fetchUrl: process.env.TARO_APP_DEV_FETCH_URL,
  },
  prod: {
    fetchUrl: process.env.TARO_APP_PROD_FETCH_URL,
  },
};
const fetchUrl: string = config[config.mode as any].fetchUrl;

export async function request<T>(requestOption: RequestOption): Promise<RequestResponse<T>> {
  return new Promise(resolve => {
    const requestResponse: RequestResponse<any> = {
      success: true,
      msg: '',
      data: null,
      response: null as any,
    };

    try {
      const requestData: RequestData = {
        url: '',
        data: {},
        header: {},
        method: 'GET',
      };
      log('request ' + JSON.stringify(requestOption));
      beforeRequest(requestData, requestOption);
      Taro.request({
        ...requestData,
        success: function (res) {
          log('request success ' + JSON.stringify(res));
          afterRequest(requestResponse, res, resolve);
        },
        fail: function (res) {
          log('request fail ' + JSON.stringify(res));
          console.log('request fail', res);
          requestResponse.success = false;
          requestResponse.msg = res.errMsg || '请求失败';
          requestResponse.response = res;
          resolve(requestResponse);
        },
      });
    } catch (error) {
      requestResponse.success = false;
      requestResponse.msg = JSON.stringify(error);
      Taro.showToast({
        icon: 'none',
        title: requestResponse.msg,
      });
      resolve(requestResponse);
    }
  });
}

export async function requestUploadFile<T>(uploadFileOption: UploadFileOption): Promise<RequestResponse<T>> {
  return new Promise(resolve => {
    const requestResponse: RequestResponse<any> = {
      success: true,
      msg: '',
      data: null,
      response: null as any,
    };
    Taro.uploadFile({
      url: fetchUrl + uploadFileOption.url,
      filePath: uploadFileOption.filePath,
      name: 'file',
      formData: uploadFileOption.formData,
      success: res => {
        afterRequest(requestResponse, res, resolve);
      },
      fail: res => {
        console.log('requestUploadFile fail', res);
        requestResponse.success = false;
        requestResponse.msg = res.errMsg || '请求失败';
        requestResponse.response = res;
        resolve(requestResponse);
      },
    });
  });
}

function beforeRequest(requestData: RequestData, requestOption: RequestOption) {
  // TODO
  // 请求前做的操作， 如url合并
  requestData.url = fetchUrl + requestOption.url;
  requestData.method = requestOption.method || 'GET';
  requestData.header = {
    ...requestData.header,
    ...requestOption.header,
  };
  requestData.data = requestOption.data;
}

function afterRequest(requestResponse: RequestResponse<any>, res: any, resolve) {
  // TODO
  // 一些特殊操作，如判断是否登录过期，然后跳转到登录

  requestResponse.success = true;
  requestResponse.data = res.data;
  requestResponse.response = res;
  requestResponse.msg = ''; // todo

  resolve(requestResponse);
}

export function fakeRequest(param: any): Promise<RequestResponse<any>> {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        success: true,
        msg: '',
        data: {},
        response: {} as any,
      });
    }, 1000);
  });
}
